package com.ruoyi.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ImageProcessor {
    public static void main(String[] args) {
        Path startPath = Paths.get("E:\\workdata\\码诚科技\\2025年\\图片生成三星\\样例\\素描\\bindi (3).png"); // 设置你要遍历的文件夹路径

        try {
            // 遍历文件夹
            Files.walk(startPath)
                    .filter(Files::isRegularFile) // 只处理文件
                    .filter(path -> path.toString().endsWith(".jpg") || path.toString().endsWith(".png")) // 只处理图片文件
                    .forEach(path -> {
                        try {
                            // 读取图片
                            BufferedImage image = ImageIO.read(path.toFile());

                            // 转换为黑白
                            BufferedImage bwImage = convertToBlackAndWhite(image);

                            // 直接覆盖原文件
                            ImageIO.write(bwImage, "jpg", path.toFile());

                            System.out.println("已处理并替换: " + path.toString());
                        } catch (IOException e) {
                            System.err.println("无法处理文件: " + path.toString());
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 将图片转换为黑白
    private static BufferedImage convertToBlackAndWhite(BufferedImage image) {
        BufferedImage bwImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Graphics g = bwImage.getGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bwImage;
    }
}

